const sharp = require('sharp')
const { PDFDocument, rgb } = require('pdf-lib')
const fs = require('fs').promises
const path = require('path')

// 添加图片水印
async function addImageWatermark(inputPath, outputPath, options = {}) {
  const { text, opacity, position } = {
    text: '标王资料网',
    opacity: 0.5,
    position: 'bottom-right',
    ...options
  }

  try {
    // 创建水印文本
    const svg = `
      <svg width="200" height="100">
        <text 
          x="50%" y="50%" 
          text-anchor="middle" 
          font-family="Arial" 
          font-size="20" 
          fill="rgba(0,0,0,${opacity})"
        >
          ${text}
        </text>
      </svg>
    `

    // 根据位置计算偏移量
    const gravityMap = {
      'top-left': 'northwest',
      'top-right': 'northeast',
      'bottom-left': 'southwest',
      'bottom-right': 'southeast',
      'center': 'center'
    }

    await sharp(inputPath)
      .composite([{
        input: Buffer.from(svg),
        gravity: gravityMap[position] || 'southeast',
        blend: 'over'
      }])
      .toFile(outputPath)

    return true
  } catch (error) {
    console.error('添加图片水印失败:', error)
    throw error
  }
}

// 添加PDF水印
async function addPDFWatermark(inputPath, outputPath, options = {}) {
  const { text, opacity, position } = {
    text: '标王资料网',
    opacity: 0.5,
    position: 'bottom-right',
    ...options
  }

  try {
    // 读取PDF文件
    const pdfBytes = await fs.readFile(inputPath)
    const pdfDoc = await PDFDocument.load(pdfBytes)
    const pages = pdfDoc.getPages()

    // 为每一页添加水印
    for (const page of pages) {
      const { width, height } = page.getSize()
      
      // 计算水印位置
      let x, y
      switch (position) {
        case 'top-left':
          x = 20
          y = height - 20
          break
        case 'top-right':
          x = width - 100
          y = height - 20
          break
        case 'bottom-left':
          x = 20
          y = 20
          break
        case 'center':
          x = width / 2 - 50
          y = height / 2
          break
        default: // bottom-right
          x = width - 100
          y = 20
      }

      // 添加水印文本
      page.drawText(text, {
        x,
        y,
        size: 20,
        color: rgb(0, 0, 0),
        opacity
      })
    }

    // 保存带水印的PDF
    const watermarkedPdf = await pdfDoc.save()
    await fs.writeFile(outputPath, watermarkedPdf)

    return true
  } catch (error) {
    console.error('添加PDF水印失败:', error)
    throw error
  }
}

// 处理文件水印
async function processWatermark(inputPath, outputPath, options) {
  const ext = path.extname(inputPath).toLowerCase()
  
  try {
    // 创建输出目录
    await fs.mkdir(path.dirname(outputPath), { recursive: true })

    if (['.jpg', '.jpeg', '.png'].includes(ext)) {
      return await addImageWatermark(inputPath, outputPath, options)
    } else if (ext === '.pdf') {
      return await addPDFWatermark(inputPath, outputPath, options)
    }

    // 不支持的文件类型直接复制
    await fs.copyFile(inputPath, outputPath)
    return true
  } catch (error) {
    console.error('处理水印失败:', error)
    throw error
  }
}

module.exports = {
  addImageWatermark,
  addPDFWatermark,
  processWatermark
}